#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/stat.h>

void printerr()
{
  fprintf(stderr, "error %d (%s)\n", errno, strerror(errno));
}

int main()
{
    const char* filename = "/tmp/log.txt";
    const char text[] = "this is sample line";
// 1. opening file
  // available std channels: STDOUT_FILENO, STDERR_FILENO
    int fd = open(filename, O_RDWR | O_CREAT , S_IRUSR | S_IWUSR);
    if (fd == -1)
    {
        printerr();
        return EXIT_FAILURE;
    }
    printf("log file was opened\n");

    int length = strlen (text);
    ssize_t result = 0;
    result = write (fd, &length, sizeof(length));
    if (result == -1)
    {
        fprintf(stderr, "failed write to fd\n");
    }

    result = write (fd, &text, length);
    if (result == -1)
    {
        fprintf(stderr, "failed write to fd\n");
    }
    printf("text was written to file\n");

    result = close (fd);
    if (result == -1)
    {
        fprintf(stderr, "failed to close fd\n");
    }

    if( (fd = open(filename, O_RDONLY)) == -1)
    {
        fprintf(stderr, "failed to open file in read-only mode\n");
    }

    length = 0;
    printf("length before read: %d\n", length);
    if ( (result = read(fd, &length, sizeof(length))) == -1)
    {
        fprintf(stderr, "failed to read from file\n");
    }
    printf("length after read: %d\n", length);

    off_t offset = lseek(fd, 0, SEEK_CUR);
    printf("offset: %d\n", (int)offset);

    char* buffer = malloc(length + 1);
    if ( (result = read(fd, buffer, length)) == -1)
    {
        fprintf(stderr, "failed to read text from file\n");
    }
    buffer[length] = 0;

    result = close (fd);
    if (result == -1)
    {
        fprintf(stderr, "failed to close fd\n");
    }

    printf("the text is: \"%s\"\n", buffer);

    return EXIT_SUCCESS;
} 
